package com.h4313.ghome.ui.fragments;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnLongClickListener;

import com.h4313.ghome.R;
import com.h4313.ghome.ui.animations.NewModuleBackgroundAnimation;

public abstract class ModuleFragment extends Fragment implements ActionMode.Callback,
		OnLongClickListener {

	protected static final String PARAM_ID = "id";
	protected static final String PARAM_NAME = "name";

	private boolean mNeedToBeInFirst = false;

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		// if (mNeedToBeInFirst) {
		// final View v = getView();
		// v.getParent().bringChildToFront(v);
		//
		// mNeedToBeInFirst = false; // prevent to be executed again, because of
		// the fragment lifecycle
		// }
		getView().setOnLongClickListener(this);
		getView().setSelected(true);

		NewModuleBackgroundAnimation animation = new NewModuleBackgroundAnimation(
				getView().findViewById(R.id.module));
		animation.animate();
	}

	public static ModuleFragment instanciate(String moduleName, int id) {

		if ("morning".equals(moduleName)) {
			return MorningConfFragment.newInstance(moduleName, id);
		} else if ("monitoring_temperature".equals(moduleName)) {
			return TemperatureFragment.newInstance(moduleName, id);
		} else if ("security".equals(moduleName)) {
			return SecurityFragment.newInstance(moduleName, id);
		} else {
			return null;
		}

	}

	public int getModuleId() {
		return getArguments().getInt(PARAM_ID);
	}

	public String getModuleName() {
		return getArguments().getString(PARAM_NAME);
	}

	public void setNeedToBeInFirst(boolean first) {
		mNeedToBeInFirst = true;
	}

	@Override
	public boolean onCreateActionMode(ActionMode mode, Menu menu) {
		mode.getMenuInflater().inflate(R.menu.menu_delete_module, menu);
		return true;
	}

	@Override
	public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_delete_module:

			if (getActivity() != null && !isDetached()) {
				FragmentTransaction tx =  getActivity().getFragmentManager().beginTransaction();
//				tx.setCustomAnimations(R.animator.new_module, R.animator.delete_module);
				tx.remove(this);
				tx.commit();
			}
			mode.finish();
			return true;
		default:
			return false;
		}
	}

	@Override
	public boolean onLongClick(View v) {

		if (getActivity() != null) {
			getActivity().startActionMode(this);
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void onDestroyActionMode(ActionMode mode) {
		getView().setSelected(false);
	}

	@Override
	public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
		return false;
	}
}
